package com.tuanzi.loan.web.bean.product.space;

import static com.tuanzi.loan.business.constants.DictionaryCode.LARGE_COMMON_PRODUCT;
import static com.tuanzi.loan.business.constants.DictionaryCode.TOPIC_TYPE;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import com.tuanzi.loan.web.configuration.OperationStatus;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.tuanzi.loan.business.entity.family.ProductInfo;
import com.tuanzi.loan.business.entity.product.space.LoanProductSpace;
import com.tuanzi.loan.business.entity.product.space.LoanProductSpaceProduct;
import com.tuanzi.loan.business.service.family.ProductInfoService;
import com.tuanzi.loan.business.service.product.space.LoanProductSpaceProductService;
import com.tuanzi.loan.business.service.product.space.LoanProductSpaceService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.ProductRule;
import com.tuanzi.loan.vo.SpaceDetails;
import com.tuanzi.loan.vo.SpaceDetails.Announcement;
import com.tuanzi.loan.web.configuration.JSFInfoBean;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

@Data
@Debug
@Slf4j
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanProductSpaceInfoBean extends JSFInfoBean<LoanProductSpace> {

	private static final long serialVersionUID = 3648871794109719001L;

	@Autowired
	private LoanProductSpaceService loanSpaceService;

	@Autowired
	private LoanProductSpaceProductService loanSpaceProductService;

	@Autowired
	private ProductInfoService productInfoService;

	private List<LoanProductSpace> topicGroup;

	private SpaceDetails spaceDetails;

	private List<LoanProductSpaceProduct> sortProducts;

	private List<ProductInfo> productInfos;

	private ProductRule productRule;

	private List<String> parentProds;

	private Long oldSpaceId;

	@PostConstruct
	private void init() {
		String id = getParamFromRequest("id");
		if (StringUtils.isNotBlank(id)) {
			$ = loanSpaceService.findOneById(Long.valueOf(id));
			oldSpaceId = $.getSpaceId();
			sortProducts = loanSpaceProductService.findAllBySpaceId($.getId());
			productRule = StringUtils.isBlank($.getProductRule()) ? null : new Gson().fromJson($.getProductRule(), ProductRule.class);
			spaceDetails = StringUtils.isBlank($.getDetails()) ? null : new Gson().fromJson($.getDetails(), SpaceDetails.class);
		} else {
			$ = new LoanProductSpace();
			oldSpaceId = null;
			$.setType(0);
			changeStatusToAdd();
		}

		if (null == productRule) {
			productRule = new ProductRule();
			productRule.getValueRule().setControlType(0);
			productRule.getFilteringRule().setHitLibFilter(true);
			productRule.getFilteringRule().setApplyConditionFilter(true);
			productRule.getFilteringRule().setJoinedFilter(false);
			productRule.getFilteringRule().setClickUvLimitationFilter(false);
			productRule.getFillRule().setAddMemberRecommend(false);
			productRule.getFillRule().setFillReadyOnlineProducts(false);
			productRule.getFillRule().setBuildBrowserTime(true);
			productRule.getSortRule().setJoinClickDown(true);
			productRule.getSortRule().setSortType(0);
			productRule.getSortRule().setApiStick(true);
			productRule.getSortRule().setValueAddBottom(false);
			productRule.getSubstitutionRule().setShowApi(true);
			productRule.getSubstitutionRule().setNoApiNoshow(false);
			productRule.getSubstitutionRule().setShowValueAdd(false);
		}

		if (null == spaceDetails) {
			spaceDetails = new SpaceDetails();
			spaceDetails.setAnnouncements(Lists.newArrayList());
		}

		if (null == sortProducts) {
			sortProducts = Lists.newArrayList();
		}

		topicGroup = loanSpaceService.findAllByType(2);
		productInfos = productInfoService.findAll();
	}

	public void onChangeSpaceType() {
		productRule.getValueRule().setControlType(0);
		spaceDetails.getAnnouncements().clear();
		if ($.getType() == 2) {
			onAddAnn();
		}
	}

	public void onAddSortProduct() {
		sortProducts.add(new LoanProductSpaceProduct());
	}

	public void onDeleteSortProduct(int index) {
		sortProducts.remove(index);
	}

	public void onAddAnn() {
		Announcement announcement = new Announcement();
		announcement.setContent("");
		spaceDetails.getAnnouncements().add(announcement);
	}

	public void onDeleteAnn(Announcement announcement) {
		spaceDetails.getAnnouncements().remove(announcement);
	}

	public void onUploadImgUrl(FileUploadEvent event) {
		spaceDetails.setImage(this.uploadImg(event.getFile()));
	}

	public void onUploadThumBnailImgUrl(FileUploadEvent event) {
		spaceDetails.setThumbnail(this.uploadImg(event.getFile()));
	}

	public void onSave() {
		if (!validation()) {
			return;
		}
		if (null == $.getId()) {
			$.setCreateTime(new Date());
		}
		if (productRule.getSubstitutionRule().getNoApiNoshow()){
            productRule.getSubstitutionRule().setSubstitutionOne(null);
            productRule.getSubstitutionRule().setSubstitutionTwo(null);
        }
		$.setDetails(StringUtils.isBlank(spaceDetails.getType()) ? null : new Gson().toJson(spaceDetails));
		$.setProductRule(new Gson().toJson(productRule));
		log.info("space:{}, rule object:{}, show product rule:{}", $.getName(), productRule, $.getProductAlgorithm());
		$ = loanSpaceService.save($, sortProducts);
		changeStatusToView();
		addSuccessfullyMessage();
	}

	public boolean validation() {
		if (StringUtils.isBlank($.getName())) {
			addErrorMessage("广告位名称不能为空");
			return false;
		}

		if (null == $.getShowCount()) {
			addErrorMessage("展示个数不能为空");
			return false;
		}

		if (null == productRule.getSortRule().getSortType()) {
			addErrorMessage("排序规则不能为空");
			return false;
		}

		if ($.getType() == 2 && StringUtils.isBlank(spaceDetails.getType())) {
			addErrorMessage("专题类型不能为空");
			return false;
		}

		if (2 == productRule.getSortRule().getSortType()) {
			if (null == productRule.getSortRule().getUvValueRatio()) {
				addErrorMessage("UV价值比例不能为空");
				return false;
			}

			if (null == productRule.getSortRule().getRemainLimitRatio()) {
				addErrorMessage("剩余控量比例不能为空");
				return false;
			}

			if ((productRule.getSortRule().getUvValueRatio() + productRule.getSortRule().getRemainLimitRatio()) != 100) {
				addErrorMessage("排序权重总比例不等于100%");
				return false;
			}
		}

		if ($.getSpaceId() == null){
			addErrorMessage("广告位ID不能为空");
			return false;
		}else{
			if (oldSpaceId == null || !oldSpaceId.equals($.getSpaceId())){
				if (loanSpaceService.findBySpaceId($.getSpaceId()) != null){
					addErrorMessage("该广告位ID已存在，不能为重复");
					return false;
				}
			}
		}
		return true;
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(TOPIC_TYPE,LARGE_COMMON_PRODUCT);
	}

}
